import { createRouter, createWebHistory } from 'vue-router'
import{ElMessage} from "element-plus"
import routes from './routes'

import homeConfig from './homeConfig'
import { loadUserMenus } from '@/api/index'
import { useBaseStore } from '@/stores/useBaseStore'

let baseStore = null

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
})

router.beforeEach(async(to,from,next)=>{
  if(baseStore==null){
    baseStore=useBaseStore()
  }
  // console.log(to.path);
  if (to.meta.isPublic) {
    next()
    return
  }

  if (baseStore.token=='') {
    next('/login')
    ElMessage.error({
      message:'请先登录'
    })
    return
  }

  // if (to.path.split('/').length < 4) {
  //   next()
  //   return
  // }

  // let isAuth = false 
  // for (let e of baseStore.menus) {
  //   if (e.right_path == to.path) {
  //     isAuth = true
  //     break
  //   }
  // }
  // if (isAuth) {
  //   // 存在授权
  //   next()
  // } else {
  //   // 不存在授权
  //   next('/home/auth')
  // }


  if (baseStore.menus.length == 0) {
    let data = await loadUserMenus()
    baseStore.menus = data
  }
  for (let m of baseStore.menus) {
    let path = m.right_path
    let name = path.replace(/^\/home/, '').replace(/\//g, '')
    if (!router.hasRoute(name)) {
      let component = homeConfig[path]
      router.addRoute('home', {
        path,
        name,
        component,
      })
    }
  }

  next()
})


export default router
